package com.dms.common.utils;

import com.alibaba.fastjson.JSON;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 阿里云短信服务工具类
 */
@Slf4j
@Component
public class DmsSmsService {

    @Value("${aliyun.sms.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.sms.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.sms.endpoint}")
    private String endpoint;

    @Value("${aliyun.sms.signName}")
    private String signName;

    @Value("${aliyun.sms.templateCode}")
    private String templateCode;

    /**
     * 创建SDK客户端
     */
    private Client createClient() throws Exception {
        Config config = new Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret)
                .setEndpoint(endpoint);
        return new Client(config);
    }

    /**
     * 发送验证码短信
     * 
     * @param phoneNumber 手机号
     * @param code 验证码
     * @return 是否发送成功
     */
    public boolean sendVerificationCode(String phoneNumber, String code) {
        try {
            // 创建SDK客户端
            Client client = createClient();
            
            // 构建短信模板参数
            Map<String, String> templateParam = new HashMap<>();
            templateParam.put("code", code);
            
            // 创建发送短信请求
            SendSmsRequest request = new SendSmsRequest()
                    .setPhoneNumbers(phoneNumber)
                    .setSignName(signName)
                    .setTemplateCode(templateCode)
                    .setTemplateParam(JSON.toJSONString(templateParam));
            
            // 发送短信
            SendSmsResponse response = client.sendSms(request);
            log.info("短信发送结果: {}", JSON.toJSONString(response));
            
            // 处理响应
            if ("OK".equals(response.getBody().getCode())) {
                log.info("短信发送成功，手机号: {}, 验证码: {}", phoneNumber, code);
                return true;
            } else {
                log.error("短信发送失败，手机号: {}, 错误信息: {}", phoneNumber, response.getBody().getMessage());
                return false;
            }
        } catch (TeaException e) {
            log.error("短信发送异常，手机号: {}, 错误码: {}, 错误信息: {}", 
                    phoneNumber, e.getCode(), e.getMessage(), e);
            return false;
        } catch (Exception e) {
            log.error("短信发送异常，手机号: {}", phoneNumber, e);
            return false;
        }
    }
} 